package org.dromara.common.excel.handler;

import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.lang.reflect.Field;

public class CustomSheetWriteDateHandler implements SheetWriteHandler {

    private  Class<T> head;
    public CustomSheetWriteDateHandler(Class head) {
        this.head = head;
    }

    @Override
    public void beforeSheetCreate(SheetWriteHandlerContext context) {
        SheetWriteHandler.super.beforeSheetCreate(context);
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        //获取工作簿
        Sheet sheet = writeSheetHolder.getSheet();
        ///开始设置下拉框
        DataValidationHelper helper = sheet.getDataValidationHelper();
        Field[] fields = head.getDeclaredFields();
        for (Field field : fields) {
            if(field.isAnnotationPresent(DateTimeFormat.class)){
                CellRangeAddressList addressList = new CellRangeAddressList(1, 65535, 7, 7);
                System.out.println("111111");
                System.out.println("Field: " + field.getName() + " has annotation: DateTimeFormat" );
                DataValidationConstraint constraint = helper.createDateConstraint(DataValidationConstraint.OperatorType.BETWEEN,"Date(1900,1,1)","Date(2099,12,31)","yyyy-MM-dd HH:mm:ss");
                DataValidation dataValidation = helper.createValidation(constraint,addressList);
                dataValidation.setShowErrorBox(true);
                dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
                dataValidation.setSuppressDropDownArrow(true);
                dataValidation.setShowPromptBox(true);
                dataValidation.createErrorBox("提示","请入时间格式为yyyy-MM-dd HH:mm:ss");
                sheet.addValidationData(dataValidation);
            }
        }
    }
}
